package com.xhl.core.social.qq.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;

/**
 * 实现QQ接口
 * AbstractOAuth2ApiBinding 抽象类，存前五部完成后获取的令牌，也就是第六步
 * @author xuhongliang
 * @date 2019/3/13
 */
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {
    /**
     * 获取openid
     */
    private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";

    /**
     * 获取用户信息
     */
    private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";
    private String appId;
    private String openId;
    //将json字符串转为java对象
    private ObjectMapper objectMapper = new ObjectMapper();

    public QQImpl(String accessToken, String appId) {
        //默认策略为 TokenStrategy.AUTHORIZATION_HEADER ，发请求默认放到请求头里，但QQ是要放到参数里的
        //ACCESS_TOKEN_PARAMETER 策略会自动把 accessToken 作为查询参数，所以获取信息时不需要给 access_token
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);

        this.appId = appId;

        //生成获取openid的url
        String url = String.format(URL_GET_OPENID, accessToken);
        //发送请求
        String result = getRestTemplate().getForObject(url, String.class);

        StaticLog.info(result);

        //对结果进行截取，获取openid
        this.openId = StrUtil.subBetween(result, "\"openid\":", "}");
    }

    @Override
    public QQUserInfo getUserInfo(){
        //生成获取用户信息的url
        String url = String.format(URL_GET_USERINFO, appId, openId);
        //发送请求
        String result = getRestTemplate().getForObject(url, String.class);

        StaticLog.info(result);

        //QQUserInfo类要参照接口返回的参数来创建属性
        try {
            return objectMapper.readValue(result, QQUserInfo.class);
        } catch (IOException e) {
            throw new RuntimeException("获取用户信息失败！");
        }
    }
}
